﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EPiServer.Data.Dynamic;
using EPiServer.Data;

namespace EPiServer.DdsPageProvider
{
	public class NodeRepository
	{
		DynamicDataStore store;

		public NodeRepository(DynamicDataStore nodeStore)
		{
			this.store = nodeStore;
		}



		public Node GetOrCreateNode(Guid pageGuid)
		{
			return Get(pageGuid)
				?? new Node(Guid.NewGuid());
		}

		public Node Get(Guid pageGuid)
		{
			return store.Items<Node>().Where(n => n.PageGuid == pageGuid).Peek();
		}

		public Node Get(Identity id)
		{
			return store.Load<Node>(id);
		}

		public IEnumerable<Identity> GetChildIdentities(string pageLink)
		{
			return store.Items<Node>()
				.Where(r => r.ParentLink == pageLink)
				.OrderBy(n => n.PeerOrder)
				.Select(n => n.Id);
		}

		public IEnumerable<Node> GetChildren(string pageLink)
		{
			return store.Items<Node>()
				.Where(r => r.ParentLink == pageLink);
		}

		public Identity Save(Node node)
		{
			node.ChangedBy = Utility.CurrentUser();
			return store.Save(node);
		}

		public void Delete(Identity id)
		{
			store.Delete(id);
		}
	}
}
